﻿using AME.Repositories;
using Microsoft.Extensions.DependencyInjection;
using System.Reflection;

namespace AME.Repository;

public static class RegisterRepositories
{
    /// <summary>
    /// 自动注册标记model的仓储
    /// </summary>
    /// <param name="externalAssembly">扫描程序集</param>
    /// <param name="services"></param>
    public static void AutoRegisterRepository(Assembly externalAssembly, IServiceCollection services)
    {
        var typesWithAutoRepository = externalAssembly.GetTypes()
            .Where(t => t.GetCustomAttributes(typeof(AutoRepository), true).Any());

        foreach (var modelType in typesWithAutoRepository)
        {
            if (modelType != null)
            {
                // 使用反射动态注册泛型仓储服务
                Type repositoryType = typeof(IBaseRepository<>).MakeGenericType(modelType);
                Type concreteRepositoryType = typeof(BaseRepository<>).MakeGenericType(modelType);
                services.AddScoped(repositoryType, concreteRepositoryType);

                // 使用反射动态注册泛型仓储服务(带审计)
                Type diffLogRepositoryType = typeof(IDiffLogRepository<>).MakeGenericType(modelType);
                Type diffLogConcreteRepositoryType = typeof(DiffLogRepository<>).MakeGenericType(modelType);
                services.AddScoped(diffLogRepositoryType, diffLogConcreteRepositoryType);
            }
        }
    }
}